using System.Web;
using System.Web.SessionState;
using Net.SourceForge.WURFL.Core;

namespace Common
{
    public class WURFLHandler : IHttpHandler, IRequiresSessionState
    {
        private readonly IWURFLManager _wurflManager;

        private const string XHTMLMP_PREFERRED_MIME_TYPE = "xhtmlmp_preferred_mime_type";
        public WURFLHandler()
        {
            _wurflManager = WURFLManagerHolder.WURFLManager;
        }

        /// <summary>
        /// Enables processing of HTTP Web requests by a custom HttpHandler that implements the <see cref="T:System.Web.IHttpHandler"/> interface.
        /// </summary>
        /// <param name="context">An <see cref="T:System.Web.HttpContext"/> object that provides references to the intrinsic server objects (for example, Request, Response, Session, and Server) used to service HTTP requests.</param>
        public void ProcessRequest(HttpContext context)
        {
            IDevice device = _wurflManager.GetDeviceForRequest(context.Request);
            string view = "App_View/Advanced/Default.aspx";

            switch (device.MarkUp)
            {
                case MarkUp.WML:
                case MarkUp.CHTML:
                    view = "App_View/WML/Default.aspx";
                    break;
                case MarkUp.XHTML_ADVANCED:
                    view = "App_View/ADVANCED/Default.aspx";
                    break;
                default:
                    view = "App_View/SIMPLE/Default.aspx";
                    break;
            }


            string contentType = device.GetCapability(XHTMLMP_PREFERRED_MIME_TYPE);

            context.Session["device"] = device;
            context.Response.ContentType = contentType;

            context.Server.Transfer(view);

        } // ProcessRequest

        /// <summary>
        /// Gets a value indicating whether another request can use the <see cref="T:System.Web.IHttpHandler"/> instance.
        /// </summary>
        /// <value></value>
        /// <returns>true if the <see cref="T:System.Web.IHttpHandler"/> instance is reusable; otherwise, false.
        /// </returns>
        public bool IsReusable
        {
            get
            {
                return true;
            } // get
        } // IsReusable property
    }
}
